package com.common.files.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.common.base.config.Global;
import com.common.files.service.IFileInfoService;
import com.common.files.service.IFileService;
import com.common.files.vo.FileInfoVO;


@Service
public class FileServiceImpl implements IFileService {
	
	@Resource
	private IFileInfoService fileInfoService;
	
	private static final String FILE_PATH = Global.getUploadPath();

	@RequestMapping(value="download")
	@Override
	public void fileDownload(Serializable fileId, Boolean download,HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		if(download==null){
			download=Boolean.TRUE;
		}
		FileInfoVO fileInfo = fileInfoService.findById(fileId);
		File f = new File(FILE_PATH,fileInfo.getFileName());
		try {
			if(download){
		        String fileName=fileInfo.getOriginalName(); 
		        resp.setCharacterEncoding("utf-8");
		        resp.setContentType("application/octet-stream");
		        String fileNameUrl = URLEncoder.encode(fileName,"UTF-8");
		        resp.setHeader("Content-Disposition", "form-data; name=\"attachment\";filename=\""+ fileNameUrl+"\"");
	        }
			
			FileInputStream fis = new FileInputStream(f);
			
			OutputStream os = resp.getOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while((length = fis.read(buffer))>0){
				os.write(buffer, 0, length);
			}
			
			os.flush();
			os.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
